package com.sgb.kjwl.view.widget;

import android.content.Context;
import android.view.View;
import android.widget.LinearLayout;

import com.bigkoo.pickerview.configure.PickerOptions;
import com.bigkoo.pickerview.listener.OnTimeSelectChangeListener;
import com.bigkoo.pickerview.view.WheelTime;
import com.contrarywind.view.WheelView;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.PopwindowLoadingTimeBinding;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.PopViewHolder;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

/**
 * Describe:    到场时间选择器（可选择时间可以小于当前时间）
 * Author:  yangLei
 * Date:    2021/9/6
 */
public class PresentTimePopWindow extends BasePopWindow implements View.OnClickListener, OnTimeSelectChangeListener {
    private PopwindowLoadingTimeBinding binding;
    //自定义控件
    private WheelTime wheelTime;
    private PickerOptions mPickerOptions;
    //当前时间
    private boolean mIsStart = true;
    private long mStartTime;
    private long mEndTime;

    public PresentTimePopWindow(Context context) {
        super(context);
    }

    @Override
    protected int popLayout() {
        return R.layout.popwindow_loading_time;
    }

    @Override
    protected void initView(PopViewHolder holder) {
        binding = (PopwindowLoadingTimeBinding) holder.getmBinding();
        //初始设置
        mPickerOptions = new PickerOptions(PickerOptions.TYPE_PICKER_TIME);
        mPickerOptions.lineSpacingMultiplier = 2.0f;
        mPickerOptions.dividerType = WheelView.DividerType.WRAP;
//        mPickerOptions.startDate = Calendar.getInstance();
        //设置时间回调
        mPickerOptions.timeSelectChangeListener = this;
        // 时间转轮 自定义控件
        initWheelTime(binding.includePicker.timePicker);
        //设置点击事件
        binding.setOnClick(this);
        //设置背景
        setBgView(binding.bgPopGrayLayout);
    }

    /**
     * 初始化时间选择器
     */
    private void initWheelTime(LinearLayout timePickerView) {
        wheelTime = new WheelTime(timePickerView, mPickerOptions.type, mPickerOptions.textGravity, mPickerOptions.textSizeContent);
        if (mPickerOptions.timeSelectChangeListener != null) {
            wheelTime.setSelectChangeCallback(() -> {
                try {
                    Date date = WheelTime.dateFormat.parse(wheelTime.getTime());
                    mPickerOptions.timeSelectChangeListener.onTimeSelectChanged(date);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            });
        }

        wheelTime.setLunarMode(mPickerOptions.isLunarCalendar);

        if (mPickerOptions.startYear != 0 && mPickerOptions.endYear != 0
                && mPickerOptions.startYear <= mPickerOptions.endYear) {
            setRange();
        }

        //若手动设置了时间范围限制
        if (mPickerOptions.startDate != null && mPickerOptions.endDate != null) {
            if (mPickerOptions.startDate.getTimeInMillis() > mPickerOptions.endDate.getTimeInMillis()) {
                throw new IllegalArgumentException("startDate can't be later than endDate");
            } else {
                setRangDate();
            }
        } else if (mPickerOptions.startDate != null) {
            if (mPickerOptions.startDate.get(Calendar.YEAR) < 1900) {
                throw new IllegalArgumentException("The startDate can not as early as 1900");
            } else {
                setRangDate();
            }
        } else if (mPickerOptions.endDate != null) {
            if (mPickerOptions.endDate.get(Calendar.YEAR) > 2100) {
                throw new IllegalArgumentException("The endDate should not be later than 2100");
            } else {
                setRangDate();
            }
        } else {//没有设置时间范围限制，则会使用默认范围。
            setRangDate();
        }

        setTime();
        wheelTime.setLabels(mPickerOptions.label_year, mPickerOptions.label_month, mPickerOptions.label_day
                , mPickerOptions.label_hours, mPickerOptions.label_minutes, mPickerOptions.label_seconds);
        wheelTime.setTextXOffset(mPickerOptions.x_offset_year, mPickerOptions.x_offset_month, mPickerOptions.x_offset_day,
                mPickerOptions.x_offset_hours, mPickerOptions.x_offset_minutes, mPickerOptions.x_offset_seconds);

        wheelTime.setCyclic(mPickerOptions.cyclic);
        wheelTime.setDividerColor(mPickerOptions.dividerColor);
        wheelTime.setDividerType(mPickerOptions.dividerType);
        wheelTime.setLineSpacingMultiplier(mPickerOptions.lineSpacingMultiplier);
        wheelTime.setTextColorOut(mPickerOptions.textColorOut);
        wheelTime.setTextColorCenter(mPickerOptions.textColorCenter);
        wheelTime.isCenterLabel(mPickerOptions.isCenterLabel);
    }

    /**
     * 设置默认时间
     */
    public void setDate(Calendar date) {
        mPickerOptions.date = date;
        setTime();
    }

    /**
     * 设置可以选择的时间范围, 要在setTime之前调用才有效果
     */
    private void setRange() {
        wheelTime.setStartYear(mPickerOptions.startYear);
        wheelTime.setEndYear(mPickerOptions.endYear);
    }

    /**
     * 设置可以选择的时间范围, 要在setTime之前调用才有效果
     */
    private void setRangDate() {
        wheelTime.setRangDate(mPickerOptions.startDate, mPickerOptions.endDate);
        initDefaultSelectedDate();
    }

    private void initDefaultSelectedDate() {
        //如果手动设置了时间范围
        if (mPickerOptions.startDate != null && mPickerOptions.endDate != null) {
            //若默认时间未设置，或者设置的默认时间越界了，则设置默认选中时间为开始时间。
            if (mPickerOptions.date == null || mPickerOptions.date.getTimeInMillis() < mPickerOptions.startDate.getTimeInMillis()
                    || mPickerOptions.date.getTimeInMillis() > mPickerOptions.endDate.getTimeInMillis()) {
                mPickerOptions.date = mPickerOptions.startDate;
            }
        } else if (mPickerOptions.startDate != null) {
            //没有设置默认选中时间,那就拿开始时间当默认时间
            mPickerOptions.date = mPickerOptions.startDate;
        } else if (mPickerOptions.endDate != null) {
            mPickerOptions.date = mPickerOptions.endDate;
        }
    }

    /**
     * 设置选中时间,默认选中当前时间
     */
    private void setTime() {
        int year, month, day, hours, minute, seconds;
        Calendar calendar = Calendar.getInstance();

        if (mPickerOptions.date == null) {
            calendar.setTimeInMillis(System.currentTimeMillis());
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            hours = calendar.get(Calendar.HOUR_OF_DAY);
            minute = calendar.get(Calendar.MINUTE);
            seconds = calendar.get(Calendar.SECOND);
        } else {
            year = mPickerOptions.date.get(Calendar.YEAR);
            month = mPickerOptions.date.get(Calendar.MONTH);
            day = mPickerOptions.date.get(Calendar.DAY_OF_MONTH);
            hours = mPickerOptions.date.get(Calendar.HOUR_OF_DAY);
            minute = mPickerOptions.date.get(Calendar.MINUTE);
            seconds = mPickerOptions.date.get(Calendar.SECOND);
        }

        wheelTime.setPicker(year, month, day, hours, minute, seconds);
    }

    /**
     * 时间选择回调
     */
    @Override
    public void onTimeSelectChanged(Date date) {
        if (mIsStart) {
            mStartTime = DateUtils.getCustomizeDayMorning(0, date.getTime()).getTime();
            binding.tvStartTime.setText(DateUtils.stampToDay(String.valueOf(mStartTime)));
        } else {
            mEndTime = DateUtils.getCustomizeDayNight(0, date.getTime()).getTime();
            binding.tvEndTime.setText(DateUtils.stampToDay(String.valueOf(mEndTime)));
        }
    }

    @Override
    public void onClick(View v) {
        if (v == binding.tvStartTime) {
            mIsStart = true;
            binding.tvStartTime.setSelected(true);
            binding.tvEndTime.setSelected(false);
            //第一次点击设置当前时间
            Date date = getCurrentTime();
            if (date != null && mStartTime == 0) {
                mStartTime = DateUtils.getCustomizeDayMorning(0, date.getTime()).getTime();
                binding.tvStartTime.setText(DateUtils.stampToDay(String.valueOf(date.getTime())));
            }
            binding.includePicker.timePicker.setVisibility(View.VISIBLE);
        } else if (v == binding.tvEndTime) {
            mIsStart = false;
            binding.tvStartTime.setSelected(false);
            binding.tvEndTime.setSelected(true);
            //第一次点击设置当前时间
            Date date = getCurrentTime();
            if (date != null && mEndTime == 0) {
                mEndTime = DateUtils.getCustomizeDayNight(0, date.getTime()).getTime();
                binding.tvEndTime.setText(DateUtils.stampToDay(String.valueOf(date.getTime())));
            }
            binding.includePicker.timePicker.setVisibility(View.VISIBLE);
        } else if (v == binding.tvReSet) {
            resetData();
        } else if (v == binding.tvOk) {
            returnData();
        }
    }

    public void resetData() {
        mStartTime = 0;
        mEndTime = 0;
        binding.tvStartTime.setText("");
        binding.tvEndTime.setText("");
        binding.tvStartTime.setSelected(false);
        binding.tvEndTime.setSelected(false);
//        setDate(Calendar.getInstance());
        binding.includePicker.timePicker.setVisibility(View.INVISIBLE);
    }

    /**
     * 获取当前时间
     */
    private Date getCurrentTime() {
        Date date = null;
        try {
            date = WheelTime.dateFormat.parse(wheelTime.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 返回数据
     */
    public void returnData() {
        //只判断两个时间都填写的情况下结束时间与开始时间的大小
        if (mStartTime != 0 && mEndTime != 0 && mEndTime < mStartTime) {
            MToast.showToast(mContext, "结束时间不能小于开始时间");
            return;
        }
        //返回数据
        onResultClick.result(mStartTime, mEndTime, null);
        dismiss();
    }
}
